﻿/*-------------------------------------------------------------------------
* CLR版本:     4.0.30319.42000
* 创建人:      song 
* 创建时间：   2024/4/9 11:58:06
* 功 能：      携程管理器
*-------------------------------------------------------------------------*/

using System.Collections;
using UnityEngine;

namespace SCore.Util
{
    public class CoRoutineExecutors
    {
        private static GameObject sGo;
        private static CoRoutineProxy sProxy;

        public static void Init()
        {
            sGo = new GameObject("__CoRoutineProxy");
            sProxy = sGo.AddComponent<CoRoutineProxy>();
            sGo.hideFlags = HideFlags.HideAndDontSave;
            GameObject.DontDestroyOnLoad(sGo);
        }

        public static Coroutine Run(IEnumerator routine)
        {
            if (routine == null)
                return null;
            return sProxy.StartCoroutine(routine);
        }

        public static void Stop(Coroutine coroutine)
        {
            if (coroutine != null)
            {
                sProxy.StopCoroutine(coroutine);
            }
        }

        public static void StopAll()
        {
            sProxy.StopAllCoroutines();
        }


        class CoRoutineProxy : MonoBehaviour
        {
            private void OnApplicationQuit()
            {
                this.StopAllCoroutines();
                if (gameObject != null)
                {
                    Destroy(this.gameObject);
                }
            }
        }
    }
}